import json
from django import forms
from django.shortcuts import render, HttpResponse
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.forms.utils import ErrorDict

from app01 import models
from app01.utils.form import BootStrapModelForm
from app01.utils.pagination import Pagination


# ajax学习
@csrf_exempt  # 免除csrf验证
def task_ajax(request):
    print(request.GET)
    # 要求csrf验证通过,@csrf_exempt解决
    print(request.POST)

    data_dict = {'status': True, "data": [11, 22, 33, 44]}
    # 1.返回方式HttpResponse
    #   json.dumps()函数是将一个Python数据类型列表进行json格式的编码,将字典转化为字符串
    return HttpResponse(json.dumps(data_dict))

    # 2.返回方式JsonResponse
    # return JsonResponse(data_dict)


class TaskModelForm(BootStrapModelForm):
    class Meta:
        model = models.Task
        fields = "__all__"
        widgets = {
            # "detail":forms.Textarea,
            "detail": forms.TextInput,
        }


@csrf_exempt
def task_list(request):
    """ 任务列表 """
    # 取数据库所有的任务
    queryset = models.Task.objects.all().order_by('id')
    form = TaskModelForm()
    page_object = Pagination(request, queryset,page_size=5)

    context = {
        "form": form,
        "queryset": page_object.page_queryset,  # 分完页数据
        "page_string": page_object.html(),  # 页码
    }
    return render(request, "task_list.html", context)


@csrf_exempt
def task_add(request):
    # print(request.POST)

    # 1.用户发送过来的数据进行校验（ModeleForm进行校验）
    form = TaskModelForm(data=request.POST)
    if form.is_valid():
        # 正确保存到数据库
        form.save()
        data_dict = {"status": True}
        return HttpResponse(json.dumps(data_dict))

    # 错误返回前端errors
    print(type(form.errors.get_json_data()))
    data_dict = {"status": False, "error": form.errors}
    return HttpResponse(json.dumps(data_dict, ensure_ascii=False))
